package com.copycoll;

import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
//import org.w3c.dom.Element;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.sax.Element;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Filelist extends ListActivity {
	/** Called when the activity is first created. */
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainlist);
		Intent intent = getIntent();
		/* ici on prends l'information des serveurs
		 */
		ServerInfos servSrce, servDest;
		try {
			servSrce = (ServerInfos)intent.getSerializableExtra("infoSrce");
			servDest = (ServerInfos)intent.getSerializableExtra("infoDest");
		}
		catch(Exception e){
			Toast.makeText(Filelist.this, "please select source or destination server", Toast.LENGTH_LONG).show(); 

		}

		ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
		final CopyFunctions cf = new CopyFunctions() ;

		//String xml = XMLfunctions.getXML(servSrce.getUrl());
		//String xml = XMLfunctions.getXML("http://10.192.170.209:8082/FileServer/GetFileList");
		//Toast.makeText(Filelist.this, (new ParseXML()).getXml(), Toast.LENGTH_LONG).show(); 
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://10.192.170.209:8082/FileServer/GetFileList");
		HttpResponse httpResponse = httpClient.execute(httpPost);

		StatusLine status = httpResponse.getStatusLine();
		if (status.getStatusCode() != 200) {
		//    Log.d(tag, "HTTP error, invalid server status code: " + resp.getStatusLine());  
		}

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(httpResponse.getEntity().getContent());
//		Document doc = XMLfunctions.XMLfromString(xml);

		int numResults = XMLfunctions.numResults(doc);

		if((numResults <= 0)){
			Toast.makeText(Filelist.this, "pas resultats", Toast.LENGTH_LONG).show();  
			finish();
		}

		NodeList nodes = doc.getElementsByTagName("file");

		for (int i = 0; i < nodes.getLength(); i++) {							
			HashMap<String, String> map = new HashMap<String, String>();	

			Element e = (Element)nodes.item(i);
			map.put("file", "file: " + XMLfunctions.getValue(e, "file"));
			//map.put("name", "Naam:" + XMLfunctions.getValue(e, "name"));
			//map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
			mylist.add(map);			
		}		

		ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.mainlist, 
				new String[] { "file", "status" }, 
				new int[] { R.id.item_title, R.id.item_subtitle });

		setListAdapter(adapter);

		final ListView lv = getListView();
		lv.setTextFilterEnabled(true);	
		lv.setOnItemClickListener(new OnItemClickListener() {
			
			/* (non-Javadoc)
			 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
			 */
			@SuppressWarnings("unchecked")


			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);	   


				try {
					if(cf.copyFile(o.get("file"), "")){

						new Thread(new Runnable() {
							/* 
							 * 
							 * recois les infos de serveur de destination
							 * en thread xml
							 * (non-Javadoc)
							 * @see java.lang.Runnable#run()
							 */
							public void run() {
								String statusxml = XMLfunctions.getXML("http://10.192.170.209:8082/FileServer/GetFileList");
								Document doc = XMLfunctions.XMLfromString(statusxml);


							}
						}).start();
						Toast.makeText(Filelist.this, "File '" + o.get("file") + "' was copied.", Toast.LENGTH_LONG).show(); 

					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}




			}
		});
	}
}